package com.prft.rms.jsf;

import javax.faces.model.DataModel;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.prft.rms.entity.Employee;
import com.prft.rms.orm.Page;
import com.prft.rms.service.EmployeeService;

@Service
public class EmployeeListDateModel extends DataModel {

	static Logger logger = LoggerFactory.getLogger(EmployeeListAction.class);

	@Autowired
	private EmployeeService employeeService;

	int pageSize = 10;
	int rowIndex;
	Page<Employee> page;
	// Triggers a fetch from the database
	protected boolean dirtyData = false;

	public EmployeeListDateModel() {

		super();
		this.rowIndex = -1;
		this.page = null;
		page = new Page<Employee>(pageSize);
		logger.debug("get new data model instance");
	}

	@Override
	public int getRowCount() {
		Long count = getPage().getTotalCount();
		return count.intValue();

	}

	@Override
	public Object getRowData() {
		int pageNo = getPageNo();
		return getPage().getResult().get(rowIndex - pageSize * (pageNo - 1));
	}

	private int getPageNo() {
		int pageNo = rowIndex / pageSize + 1;
		return pageNo;
	}

	@Override
	public int getRowIndex() {
		return rowIndex;
	}

	@Override
	public Object getWrappedData() {
		logger.debug("get wrap data " + rowIndex);
		return getPage().getResult();
	}

	@Override
	public boolean isRowAvailable() {
		return getPage().isHasNext();
	}

	@Override
	public void setRowIndex(int index) {
		//		logger.debug("page row index :" + index);
		rowIndex = index;

	}

	@Override
	public void setWrappedData(Object arg0) {
		// TODO Auto-generated method stub

	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public Page<Employee> getPage() {

		int pageNo = getPageNo();

		boolean empty = (page.getResult().size() == 0);
		boolean changedPage = (rowIndex > -1) && (page.getPageNo() != pageNo);
		if (empty || changedPage || dirtyData) {
			logger.debug("get page data for employee " + this.toString());
			logger.debug("rowindex" + rowIndex);
			logger.debug(page.getPageNo() + " " + pageNo);
			page.setPageNo(pageNo);
			employeeService.getPage(page);
		}
		return page;
	}

	public void setPage(Page<Employee> page) {
		this.page = page;
	}

	public boolean isDirtyData() {
		return dirtyData;
	}

	public void setDirtyData(boolean dirtyData) {
		logger.debug("set dirtyData" + dirtyData);
		this.dirtyData = dirtyData;
	}

	public EmployeeService getEmployeeService() {
		return employeeService;
	}

	public void setEmployeeService(EmployeeService employeeService) {
		this.employeeService = employeeService;
	}

}
